<template>
  <div class="car-page-wrapper">
    <div class="header">
      <div class="search">
        <a-input
          :style="{ width: '320px' }"
          placeholder="按下Enter进行搜索"
          allow-clear
          @change="handleSearch"
        />
        <a-button type="primary" @click="handleSearch">搜索</a-button>
      </div>

      <template v-if="userInfo?.role === 2 || userInfo?.status === 'admin'">
        <div class="operations">
          <a-button @click="() => setModalVisible(true)">添加活动</a-button>
        </div>
      </template>
    </div>

    <div class="body">
      <div class="line">
        <div class="label">我加入的活动</div>
        <div class="content">
          <template v-for="item in enteredList" :key="item.id">
            <carCard :data="item">
              <template #default>
                <div>名称：{{ item.activityName }}</div>
                <div>开始时间：{{ item.deadline }}</div>
                <div>地点：{{ item.location }}</div>
                <div>介绍：{{ item.activityDescribe }}</div>
                <div class="buttons">
                  <a-button @click="exit({ id: item.id })" type="danger">
                    退出
                  </a-button>
                </div>
              </template>
            </carCard>
          </template>
        </div>
      </div>

      <div class="line">
        <div class="label">附近的活动</div>
        <div class="content">
          <template v-for="item in filteredData" :key="item.id">
            <carCard :data="item">
              <template #default>
                <div>名称：{{ item.activityName }}</div>
                <div>开始时间：{{ item.deadline }}</div>
                <div>地点：{{ item.location }}</div>
                <div>介绍：{{ item.activityDescribe }}</div>

                <div class="buttons">
                  <a-button @click="join(item)">加入</a-button>
                  <template v-if="userInfo?.id === item.userId">
                    <a-button
                      @click="handleExit({ id: item.id })"
                      type="danger"
                    >
                      删除
                    </a-button>
                  </template>
                </div>
              </template>
            </carCard>
          </template>
        </div>
      </div>
    </div>

    <modal :setVisible="setModalVisible" :visible="modalVisible">
      <a-form :model="form" @submit="handleSubmit">
        <a-form-item field="model" label="活动封面图">
          <template v-if="!filePicUrl">
            <a-upload
              @before-upload="customRequest"
              :limit="1"
              :show-file-list="false"
            >
              <template #upload-button>
                <template v-if="!filePicUrl">
                  <a-button>点击上传</a-button>
                </template>
              </template>
            </a-upload>
          </template>

          <template v-else>
            <div class="preview">
              <img :src="filePicUrl" alt="上传的图片" />
              <div class="preview-delete" @click="filePicUrl = ''">删除</div>
            </div>
          </template>
        </a-form-item>

        <a-form-item field="activityName" label="活动名称">
          <a-input v-model="form.activityName" placeholder="请输入名称" />
        </a-form-item>
        <a-form-item field="model" label="活动描述">
          <a-input v-model="form.activityDescribe" placeholder="请输入描述" />
        </a-form-item>
        <a-form-item field="model" label="开始时间">
          <a-input v-model="form.deadline" placeholder="请输入日期" />
        </a-form-item>
        <a-form-item field="model" label="地点">
          <a-input v-model="form.location" placeholder="请输入地点" />
        </a-form-item>

        <a-form-item>
          <a-button html-type="submit">提交</a-button>
        </a-form-item>
      </a-form>
    </modal>
  </div>
</template>

<script setup lang="ts">
import carCard from "@/components/oldman/car-card/index.vue";
import { commonRequest } from "@/utils/request";
import { onMounted } from "vue";
import modal from "@/components/common/modal/index.vue";
import { ref } from "vue";
import { reactive } from "vue";
import { Message } from "@arco-design/web-vue";
import {
  addActivity,
  enterActivity,
  enteredActivity,
  exitActivity,
  exitActivity2,
  getActivityList,
} from "@/apis/oldman";
import dayjs from "dayjs";
import { oldmanUploadRequest } from "@/apis/oldman/base";

const baseForm = {
  activityName: "",
  activityDescribe: "",
  deadline: "2025-05-29 01:55:58",
  location: "",
};

const filePicUrl = ref();
const allData = ref(null);
const filteredData = ref([]);
const modalVisible = ref(false);
const form = reactive(baseForm);
const userInfo = ref(null);
const enteredList = ref([]);

const customRequest = async (data) => {
  const formData = new FormData();
  formData.append("file", data);
  const res = await oldmanUploadRequest("onlyLoad", formData);
  filePicUrl.value = res.data.data;

  // console.log("filePicUrl", filePicUrl.value);
  return true;
};

const getData = async () => {
  const res = await getActivityList();
  const res1 = await getDataAlreadyEntered();
  allData.value = res.data.data;
  filteredData.value = allData.value;
  enteredList.value = res1.data.data;
};

const setModalVisible = (v: boolean) => {
  modalVisible.value = v;
};

const handleExit = async (id) => {
  const res = await exitActivity(id);
  if (res.data.code === 200) {
    Message.success("删除成功");
    getData();
  }
  getData();
};

const exit = async (id) => {
  const res = await exitActivity2(id);
  if (res.data.code === 200) {
    Message.success("退出成功");
    getData();
  }
};

const sendFormData = async () => {
  const data = {
    ...form,
    picture: filePicUrl.value,
  };
  const res = await addActivity(data as any);
  if (res.data.code === 200) {
    Message.success("添加成功");
  }
};

const handleSubmit = async () => {
  await sendFormData();
  setModalVisible(false);
  getData();
};

const handleSearch = (value: string) => {
  if (value) {
    const v = value.toLowerCase();
    filteredData.value = allData.value.filter((item: any) => {
      return (
        item.description.toLowerCase().includes(v) ||
        item.bodytype.toLowerCase().includes(v) ||
        item.fueltype.toLowerCase().includes(v) ||
        item.exteriorcolor.toLowerCase().includes(v) ||
        item.interiorcolor.toLowerCase().includes(v)
      );
    });
  } else {
    filteredData.value = allData.value;
  }
};

const getDataAlreadyEntered = async () => {
  const res = await enteredActivity();
  return res;
};

const join = async (item: any) => {
  const res = await enterActivity({ id: item.id });
  if (res.data.code === 200) {
    Message.success("添加成功");
    getData();
  }
};

onMounted(() => {
  const userInfoJSON = localStorage.getItem("userInfo");
  userInfo.value = JSON.parse(userInfoJSON);
  getData();
});
</script>

<style scoped>
.header {
  padding: 0 24px;
  display: flex;
  justify-content: space-between;
}

.search {
  display: flex;
  justify-content: flex-start;
  gap: 12px;
}

.car-page-wrapper {
  display: flex;
  flex-direction: column;
  gap: 24px;
}
.body {
  padding: 24px;
}

.line {
  margin-top: 24px;
}

.label {
  font-weight: 800;
  padding: 8px 0;
}

.content {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  gap: 12px;
}

.time-wrapper {
  display: flex;
  justify-content: space-around;
}

.buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.preview {
  position: relative;
}
.preview-delete {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  color: white;
  font-size: 12px;
  font-weight: 800;
  opacity: 0;
  transition: 0.1s linear;
  cursor: pointer;
}
.preview-delete:hover {
  opacity: 1;
}
</style>
